const { Users, validateUser } = require('../../model/user')
const bcrypt = require('bcryptjs');

module.exports = async(req, res, next) => {

    try {
        await validateUser(req.body)
    } catch (ex) {
        return next(JSON.stringify({ path: '/admin/user-edit', message: ex.message }))

    }
    const user = await Users.findOne({ email: req.body.email });
    if (user) {
        return next(JSON.stringify({ path: '/admin/user-edit', message: "邮箱地址被占用" }))
    } else {
        const salt = await bcrypt.genSalt(10);
        const password = await bcrypt.hash(req.body.password, salt);
        req.body.password = password;
        await Users.create(req.body);
        res.redirect('/admin/user')

    }

}